package xyz.ljcc.ccmt.service.impl.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import xyz.ljcc.ccmt.commons.utils.UpdateTool;
import xyz.ljcc.ccmt.model.base.Dept;
import xyz.ljcc.ccmt.repository.admin.DeptRepository;
import xyz.ljcc.ccmt.service.api.admin.DeptService;

@Service
public class DeptServiceImpl implements DeptService {

	@Autowired
	DeptRepository deptRepository;
	
	@Override
	public List<Dept> getDeptsByloginName(String loginName) {
		return deptRepository.loadByLoginName(loginName);
	}

	@Override
	public List<Dept> getDepts(String deptName) {
		if(StringUtils.isEmpty(deptName)) {
			return deptRepository.findAll();
		}else {
			return deptRepository.getByDeptNameContaining(deptName);
		}
	}

	@Override
	public void activeDept(Integer id, Integer active) {
		deptRepository.updateByHql("update Dept d set d.active = ?1 where d.id = ?2"
				, active
				, id);
	}

	@Override
	public Dept getDeptById(Integer id) {
		return deptRepository.findOne(id);
	}

	@Override
	public Dept saveDept(Dept dept) {
		if(dept.getActive() == null) // 默认设置成启用状态
			dept.setActive(1);
		return  deptRepository.save(dept);
	}

	@Override
	public Dept editDept(Dept dept) {
		Dept dept1 = deptRepository.findOne(dept.getId());
		UpdateTool.copyNullProperties(dept1, dept);
		return deptRepository.save(dept);
	}

	@Override
	public void delDept(Integer id) {
		deptRepository.delete(id);
	}

}
